import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());

  return {
    server: {
      // 允许IP访问
      host: "0.0.0.0",
      // 前端的端口号
      port: Number(process.env.VITE_APP_PORT) || 3000,
      // 是否自动打开浏览器
      open: false,
      proxy: {
        // 代理配置
        [env.VITE_APP_BASE_API]: {
          // 是否跨域
          changeOrigin: true,
          // 代理目标地址 
          target: env.VITE_APP_API_URL,
          rewrite: (path) => 
            // 重写路径，将前缀去掉
            path.replace(new RegExp("^" + env.VITE_APP_BASE_API), ""),
        },
      },
    },
    plugins: [
      vue(),
      vueDevTools(),
      // element-plus 自动导入
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
        ],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          // api: 'modern-compiler',
          additionalData:
            `
            @use "@/styles/variables.scss" as *;  
            `
        }
      }
    },
  }
})
